package controllers

import (
	"MyWebServer/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/session" //session的使用
)

type LoginController struct {
	beego.Controller
}

//全局session变量
//var globalSessions *session.Manager
//初始化
func init() {
	globalSessions, _ := session.NewManager("memory", `{"cookieName":"gosessionid","enableSetCookie,omitempty":true,"gclifetime":3600,"maxLifetime":3600,"secure":false,"sessionIDHashFunc":"sha1","sessionIDHashKey":"","cookieLifeTime":3600,"providerConfig":""}`)
	go globalSessions.GC()
}

//显示登陆界面
func (this *LoginController) Get() {
	this.Layout = "layout.html"
	this.TplNames = "login.html"
}

//处理登陆请求
func (this *LoginController) Post() {
	inputs := this.Input()             //获取HTML数据
	username := inputs.Get("username") //用户名
	password := inputs.Get("password") //密码
	//base64加密
	newPass := models.EncryptionParams([]byte(password))
	userInfo := models.GetAll() //获取信息
	if userInfo.UserName == username {
		if userInfo.Password == newPass {
			//登陆成功设置session
			sess := this.StartSession()
			defer sess.SessionRelease(this.Ctx.ResponseWriter)
			sess.Set("username", username)
			this.Ctx.Redirect(302, "/home")
		} else {
			this.Data["Prompt"] = "密码错误!"
			//this.Ctx.Redirect(302, "/")
			this.Layout = "layout.html"
			this.TplNames = "login.html"
		}
	} else {
		this.Data["Prompt"] = "用户名错误!"
		//this.Ctx.Redirect(302, "/")
		this.Layout = "layout.html"
		this.TplNames = "login.html"
	}
}
